package com.sita.cfmoto.interact.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;

import com.amap.api.location.AMapLocation;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapOptions;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyTrafficStyle;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.sita.cfmoto.R;
import com.sita.cfmoto.shouye.LocationSearchActivity;
import com.sita.cfmoto.support.Constants;
import com.sita.cfmoto.support.GlobalContext;
import com.sita.cfmoto.utils.BitmapUtils;
import com.sita.cfmoto.utils.AMapUtil;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ReleaseActiveMapActivity extends AppCompatActivity implements AMap.OnMapLongClickListener {
    @Bind(R.id.map)
    MapView mMapView;
    private AMap aMap;
    private Marker myMarker, locationMarker;
    private LatLng mLocation;
    private String mLocationString;
    private int iconSize;


    public static Intent newIntent (Context context, LatLng latLng, String location){
        Intent intent = new Intent(context, ReleaseActiveMapActivity.class);
        intent.putExtra("latlng", latLng);
        intent.putExtra("location", location);
        return intent;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_release_active_map);
        ButterKnife.bind(this);
        mMapView.onCreate(savedInstanceState);// 此方法必须重写
        initMap();
        Intent intent = getIntent();
        if (intent!=null ) {
            mLocationString =  intent.getStringExtra("location");
            mLocation =  intent.getParcelableExtra("latlng");
        }
        if (mLocation!=null) {
            drawLocationMarker(mLocation);
            showMarkerInfo(mLocationString);
        }else {
            showMyMarker();
        }
    }

    private void initMap() {
        if (aMap == null) {
            aMap = mMapView.getMap();
            UiSettings mUiSettings = aMap.getUiSettings();
            mUiSettings.setZoomControlsEnabled(false);
            mUiSettings.setLogoPosition(AMapOptions.LOGO_POSITION_BOTTOM_LEFT);
            mUiSettings.setScrollGesturesEnabled(true);

            MyTrafficStyle myTrafficStyle = new MyTrafficStyle();
            myTrafficStyle.setSeriousCongestedColor(0xff92000a);
            myTrafficStyle.setCongestedColor(0xffea0312);
            myTrafficStyle.setSlowColor(0xffff7508);
            myTrafficStyle.setSmoothColor(0xff00a209);
            aMap.setTrafficEnabled(false);
        }

        iconSize = (int) getResources().getDimension(R.dimen.map_icon_size_small);

        aMap.setOnMapLongClickListener(this);
    }

    private void showMyMarker() {
        LatLng latLng;
        AMapLocation location = GlobalContext.getLocationClient().getLastKnownLocation();
        if (location != null) {
            latLng = new LatLng(location.getLatitude(), location.getLongitude());
            drawMyMarker(latLng);
            moveCamera(latLng);
        }

    }

    public void drawMyMarker(LatLng latLng) {
        if (myMarker == null) {
            Bitmap locationMe = BitmapUtils.zoomBitmap(BitmapFactory.decodeResource(
                    GlobalContext.getGlobalContext().getResources(), R.drawable.location_me),
                    iconSize, iconSize);
            BitmapDescriptor icon = BitmapDescriptorFactory.fromBitmap(locationMe);
            myMarker = aMap.addMarker(new MarkerOptions().draggable(false).icon(icon)
                    .position(latLng).title(getString(R.string.my_location)));
        } else {
            myMarker.setPosition(latLng);
        }
    }

    private void moveCamera(LatLng latLng) {
        CameraPosition cameraPosition;
        cameraPosition = new CameraPosition.Builder()
                .target(latLng).zoom(Constants.DEFAULT_ZOOM_LEVEL).bearing(0).tilt(0).build();
        CameraUpdate update = CameraUpdateFactory.newCameraPosition(cameraPosition);
        aMap.moveCamera(update);
    }

    private void drawLocationMarker(LatLng latLng) {
        if (locationMarker == null) {
            Bitmap location = BitmapUtils.zoomBitmap(BitmapFactory.decodeResource(
                    GlobalContext.getGlobalContext().getResources(), R.mipmap.location_icon),
                    iconSize, iconSize);
            BitmapDescriptor icon = BitmapDescriptorFactory.fromBitmap(location);
            locationMarker = aMap.addMarker(new MarkerOptions().draggable(false).icon(icon)
                    .position(latLng));
        } else {
            locationMarker.setPosition(latLng);
        }

        aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
                latLng, 15));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        handleResult(requestCode, resultCode, data);
    }

    private void handleResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == 1) {
            mLocationString = data.getStringExtra("location") + "附近";
            LatLonPoint latLonPoint = data.getParcelableExtra("latLonPoint");
            mLocation = AMapUtil.convertToLatLng(latLonPoint);
            drawLocationMarker(mLocation);
            showMarkerInfo(mLocationString);
        }
    }

    private void onOkLocation() {
        Intent intent = new Intent();
        if (TextUtils.isEmpty(mLocationString)) {
            ReleaseActiveMapActivity.this.setResult(RESULT_CANCELED);
        }else {
            intent.putExtra("LatLon", mLocation);
            intent.putExtra("Address", mLocationString);
            ReleaseActiveMapActivity.this.setResult(RESULT_OK, intent);
        }
        this.finish();
    }

    private void onGeocode(LatLng latLng) {
        GeocodeSearch geocoderSearch = new GeocodeSearch(this);
        geocoderSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
            @Override
            public void onRegeocodeSearched(RegeocodeResult result, int rCode) {
                if (rCode == 1000) {
                    if (result != null && result.getRegeocodeAddress() != null
                            && result.getRegeocodeAddress().getFormatAddress() != null) {
                        mLocationString = result.getRegeocodeAddress().getFormatAddress()
                                + "附近";
                        showMarkerInfo(mLocationString);
                    } else {
                    }
                } else {
                }
            }

            @Override
            public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

            }
        });

        LatLonPoint point = AMapUtil.convertToLatLonPoint(latLng);
        RegeocodeQuery query = new RegeocodeQuery(point, 100, GeocodeSearch.AMAP);

        geocoderSearch.getFromLocationAsyn(query);
    }

    private void showMarkerInfo(String info) {
        if (locationMarker!=null) {
            locationMarker.setSnippet(info);
            locationMarker.showInfoWindow();
        }
    }

    @Override
    public void onMapLongClick(LatLng latLng) {
        mLocation = latLng;
        drawLocationMarker(latLng);
        onGeocode(latLng);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        ReleaseActiveMapActivity.this.setResult(RESULT_CANCELED);
    }

    @OnClick({R.id.back_img})
    void onBack() {
        onBackPressed();
    }

    @OnClick(R.id.ok)
    void onOk() {
        onOkLocation();
    }

    @OnClick(R.id.search)
    void onSearch(){
        Intent intent = new Intent();
        intent.setClass(this, LocationSearchActivity.class);
        startActivityForResult(intent, 1);
    }
}
